﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MachineBuildingSystem
{
    public partial class DB2CfgForm : XtraForm
    {
        public DB2CfgForm()
        {
            InitializeComponent();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtServerIP.Text.Trim()))
            {
                MessageBox.Show("数据库IP地址不能为空！");
                txtServerIP.Focus();
                return;
            }
            if (string.IsNullOrEmpty(txtDSN.Text.Trim()))
            {
                MessageBox.Show("DSN名称不能为空！");
                txtDSN.Focus();
                return;
            }
            if (string.IsNullOrEmpty(txtUser.Text.Trim()))
            {
                MessageBox.Show("用户名不能为空！");
                txtUser.Focus();
                return;
            }
            if (string.IsNullOrEmpty(txtPassword.Text.Trim()))
            {
                MessageBox.Show("密码不能为空！");
                txtPassword.Focus();
                return;
            }
            //修改配置文件的数据文件密码字段
            Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            string connectionStr = "Server=" + txtServerIP.Text.Trim()
                + ";DSN=" + txtDSN.Text.Trim()
                + ";UID=" + txtUser.Text.Trim()
                + ";PWD=" + CommonHelper.Encrypt(txtPassword.Text.Trim(), "tp_ltscm")
                + ";Protocol=TCPIP";
            cfa.AppSettings.Settings["DB2ConnectionStr"].Value = connectionStr;//设置config的值
            cfa.Save();
            ConfigurationManager.RefreshSection("appSettings");
            MessageBox.Show(this, "配置DB2数据库成功！");
            this.Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void DB2CfgForm_Load(object sender, EventArgs e)
        {
            string connectionStr = ConfigurationManager.AppSettings["DB2ConnectionStr"].ToString();
            string[] strArr = connectionStr.Split(';');
            foreach (string item in strArr)
            {
                if (item.StartsWith("Server"))
                    txtServerIP.Text = item.Substring("Server=".Length);
                if (item.StartsWith("DSN"))
                    txtDSN.Text = item.Substring("DSN=".Length);
                if (item.StartsWith("UID"))
                    txtUser.Text = item.Substring("UID=".Length);
                if (item.StartsWith("PWD"))
                    txtPassword.Text = CommonHelper.Decrypt(item.Substring("PWD=".Length), "tp_ltscm");
            }
        }
    }
}
